<template>
  <div class="cart-container">
    <div class="cart-header">
      <h2>我的购物车</h2>
      <div class="cart-actions">
        <el-button type="primary" :disabled="!selectedItems.length" @click="handleCheckout">
          结算 ({{ selectedItems.length }})
        </el-button>
        <el-button :disabled="!selectedItems.length" @click="handleBatchDelete">
          删除选中
        </el-button>
        <el-button @click="handleClear">清空购物车</el-button>
      </div>
    </div>

    <!-- 购物车列表 -->
    <el-table
      v-loading="loading"
      :data="cartList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column label="商品信息" min-width="400">
        <template #default="{ row }">
          <div class="product-info">
            <el-image
              :src="row.productImage"
              :preview-src-list="[row.productImage]"
              fit="cover"
              class="product-image"
            />
            <div class="product-detail">
              <h3 class="product-name">{{ row.productName }}</h3>
              <p class="product-spec">{{ row.specification }}</p>
              <div class="product-tags" v-if="row.tags?.length">
                <el-tag
                  v-for="tag in row.tags"
                  :key="tag"
                  size="small"
                  :type="tag.type"
                >
                  {{ tag.label }}
                </el-tag>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="单价" width="120" align="center">
        <template #default="{ row }">
          <span class="price">¥{{ row.price.toFixed(2) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="数量" width="150" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.quantity"
            :min="1"
            :max="row.stock"
            :disabled="row.stock <= 0"
            @change="(value) => handleQuantityChange(row, value)"
          />
          <div class="stock-info" v-if="row.stock <= 5">
            仅剩 {{ row.stock }} 件
          </div>
        </template>
      </el-table-column>

      <el-table-column label="小计" width="120" align="center">
        <template #default="{ row }">
          <span class="subtotal">¥{{ (row.price * row.quantity).toFixed(2) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="120" align="center">
        <template #default="{ row }">
          <el-button
            type="danger"
            link
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 购物车为空 -->
    <el-empty
      v-if="!loading && !cartList.length"
      description="购物车还是空的"
    >
      <el-button type="primary" @click="$router.push('/products')">
        去购物
      </el-button>
    </el-empty>

    <!-- 购物车底部 -->
    <div class="cart-footer" v-if="cartList.length">
      <div class="cart-summary">
        <div class="selected-info">
          已选择 <span class="highlight">{{ selectedItems.length }}</span> 件商品
        </div>
        <div class="total-info">
          合计：<span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
      </div>
      <el-button
        type="primary"
        size="large"
        :disabled="!selectedItems.length"
        @click="handleCheckout"
      >
        结算 ({{ selectedItems.length }})
      </el-button>
    </div>

    <!-- 推荐商品 -->
    <div class="recommend-products" v-if="recommendList.length">
      <h3>猜你喜欢</h3>
      <el-row :gutter="20">
        <el-col
          v-for="item in recommendList"
          :key="item.id"
          :xs="12"
          :sm="8"
          :md="6"
          :lg="4"
        >
          <el-card
            class="product-card"
            :body-style="{ padding: '0px' }"
            @click="handleAddToCart(item)"
          >
            <el-image
              :src="item.image"
              fit="cover"
              class="product-image"
            />
            <div class="product-info">
              <h4 class="product-name">{{ item.name }}</h4>
              <p class="product-price">¥{{ item.price.toFixed(2) }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getCartList,
  updateCartItem,
  deleteCartItem,
  batchDeleteCartItems,
  clearCart,
  addToCart,
  getRecommendProducts
} from '@/api/cart'

const router = useRouter()

// 状态
const loading = ref(false)
const cartList = ref<any[]>([])
const selectedItems = ref<any[]>([])
const recommendList = ref<any[]>([])

// 计算属性
const totalAmount = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + item.price * item.quantity
  }, 0)
})

// 获取购物车列表
const loadCartList = async () => {
  try {
    loading.value = true
    const res = await getCartList()
    cartList.value = res.data
  } catch (error) {
    console.error('获取购物车列表失败:', error)
    ElMessage.error('获取购物车列表失败')
  } finally {
    loading.value = false
  }
}

// 获取推荐商品
const loadRecommendProducts = async () => {
  try {
    const res = await getRecommendProducts()
    recommendList.value = res.data
  } catch (error) {
    console.error('获取推荐商品失败:', error)
  }
}

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedItems.value = selection
}

// 处理数量变化
const handleQuantityChange = async (item: any, quantity: number) => {
  try {
    await updateCartItem({
      id: item.id,
      quantity
    })
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('更新数量失败:', error)
    ElMessage.error('更新数量失败')
    // 恢复原数量
    item.quantity = item.quantity
  }
}

// 处理删除
const handleDelete = async (item: any) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该商品吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteCartItem(item.id)
    ElMessage.success('删除成功')
    await loadCartList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理批量删除
const handleBatchDelete = async () => {
  if (!selectedItems.value.length) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedItems.value.length} 件商品吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedItems.value.map(item => item.id)
    await batchDeleteCartItems(ids)
    ElMessage.success('删除成功')
    await loadCartList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 处理清空购物车
const handleClear = async () => {
  if (!cartList.value.length) return
  
  try {
    await ElMessageBox.confirm(
      '确定要清空购物车吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await clearCart()
    ElMessage.success('清空成功')
    await loadCartList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空购物车失败:', error)
      ElMessage.error('清空购物车失败')
    }
  }
}

// 处理结算
const handleCheckout = () => {
  if (!selectedItems.value.length) return
  
  const ids = selectedItems.value.map(item => item.id)
  router.push({
    path: '/order/confirm',
    query: { items: ids.join(',') }
  })
}

// 处理添加到购物车
const handleAddToCart = async (product: any) => {
  try {
    await addToCart({
      productId: product.id,
      quantity: 1
    })
    ElMessage.success('添加成功')
    await loadCartList()
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败')
  }
}

// 初始化
onMounted(() => {
  loadCartList()
  loadRecommendProducts()
})
</script>

<style lang="scss" scoped>
.cart-container {
  padding: 20px;
  
  .cart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 24px;
      font-weight: 500;
    }
    
    .cart-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .product-info {
    display: flex;
    align-items: center;
    gap: 15px;
    
    .product-image {
      width: 80px;
      height: 80px;
      border-radius: 4px;
    }
    
    .product-detail {
      flex: 1;
      
      .product-name {
        margin: 0 0 8px;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
      
      .product-spec {
        margin: 0 0 8px;
        font-size: 14px;
        color: #909399;
      }
      
      .product-tags {
        display: flex;
        gap: 5px;
      }
    }
  }
  
  .price,
  .subtotal {
    font-size: 16px;
    font-weight: 500;
    color: #f56c6c;
  }
  
  .stock-info {
    margin-top: 5px;
    font-size: 12px;
    color: #f56c6c;
  }
  
  .cart-footer {
    position: sticky;
    bottom: 0;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 20px;
    margin-top: 20px;
    padding: 15px 20px;
    background: #fff;
    border-top: 1px solid #dcdfe6;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    
    .cart-summary {
      display: flex;
      align-items: center;
      gap: 20px;
      
      .selected-info {
        font-size: 14px;
        color: #606266;
        
        .highlight {
          color: var(--el-color-primary);
          font-weight: 500;
        }
      }
      
      .total-info {
        font-size: 14px;
        color: #606266;
        
        .total-price {
          font-size: 20px;
          font-weight: 500;
          color: #f56c6c;
        }
      }
    }
  }
  
  .recommend-products {
    margin-top: 40px;
    
    h3 {
      margin: 0 0 20px;
      font-size: 18px;
      font-weight: 500;
    }
    
    .product-card {
      margin-bottom: 20px;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      }
      
      .product-image {
        width: 100%;
        height: 200px;
      }
      
      .product-info {
        padding: 10px;
        
        .product-name {
          margin: 0 0 8px;
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          @include text-ellipsis;
        }
        
        .product-price {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
          color: #f56c6c;
        }
      }
    }
  }
}

// 响应式设计
@media screen and (max-width: 768px) {
  .cart-container {
    .cart-header {
      flex-direction: column;
      gap: 15px;
      align-items: flex-start;
      
      .cart-actions {
        width: 100%;
        justify-content: space-between;
      }
    }
    
    .cart-footer {
      flex-direction: column;
      gap: 15px;
      
      .cart-summary {
        width: 100%;
        justify-content: space-between;
      }
      
      .el-button {
        width: 100%;
      }
    }
  }
}
</style> 